<?php

namespace App\Http\Controllers\System;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use \Cache;

class LoginController extends Controller
{

    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }

    /**
     *登录页面
     */

    public function index()
    {
        return view('system.login');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Psr\Http\Message\StreamInterface
     */
    public function login()
    {
        $params['username'] = request('name');
        $params['password'] = request('psd');

        try{
            $user = callApiServer("System.UserService.userLogin", $params);

            if(!$user){
                return response()->json(['code'=>400,'data'=>'用户名或密码错误！']);
            }
            //登录成功
            //获取用户菜单
            $menus = callApiServer("System.UserService.getUserMenu", ['user_id'=>$user['id']]);
            $user['menus'] = $menus;
            session()->put('userinfo', $user);
            return response()->json(['code'=>200,'data'=>'/main']);
        }catch (\Exception $e){
            if($e->getCode() == 500){
                return response()->json(['code'=>400,'data'=>'后台服务异常:'.$e->getMessage()]);
            }else{
                return response()->json(['code'=>400,'data'=>$e->getMessage()]);
            }
        }
    }

    public function logout()
    {
        session()->forget('userinfo');
        return response()->json();
    }
}

